<template>
  <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
    <h2 class="sub-header">添加留言</h2>
    <div class="form-group">
      <label for="name">姓名</label>
      <input
        type="text"
        class="form-control"
        id
        v-model="info.name"
        name="name"
        required
        minlength="2"
        maxlength="10"
        placeholder="请输入姓名"
      />
    </div>
    <div class="form-group">
      <label for>内容</label>
      <textarea
        class="form-control"
        type="text"
        rows="10"
        id
        v-model="info.msg"
        placeholder="请输入留言内容"
        name="msg"
        required
      ></textarea>
    </div>
    <button @click="doSubmit" class="btn btn-primary">发布</button>
    <router-link class="btn btn-danger" to="/msg">取消</router-link>
  </div>
</template>
<script>
import { addMsgData, getMsgData } from "@/apis/data";
import { Toast } from "mint-ui";
export default {
  data() {
    return {
      info: {}
    };
  },
  methods: {
    getInfos() {
      getMsgData().then(res => {
        this.infos = res.data;
      });
    },
    doSubmit() {
      addMsgData(this.info)
        .then(response => {
          if (this.info.name == "" || this.info.msg == "") {
            return;
          }
          var data = response.data;
          if (data.code == 0) {
            this.info = {};
            this.getInfos();
            this.$router.push("/msg");
            Toast({
              message: "发表成功！",
              position: "middle",
              duration: 1000,
              iconClass: "glyphicon glyphicon-ok"
            });
          } else if (data.code == 1) {
            Toast({
              message: "姓名不能为空！",
              position: "middle",
              duration: 1000,
              iconClass: "glyphicon glyphicon-remove"
            });
          } else if (data.code == 2) {
            Toast({
              message: "留言不能为空！",
              position: "middle",
              duration: 1000,
              iconClass: "glyphicon glyphicon-remove"
            });
          } else if (data.code == 3) {
            Toast({
              message: "姓名必须2-10位字符",
              position: "middle",
              duration: 1000,
              iconClass: "glyphicon glyphicon-remove"
            });
          } else if (data.code == 4) {
            Toast({
              message: "姓名必须4-100位字符",
              position: "middle",
              duration: 1000,
              iconClass: "glyphicon glyphicon-remove"
            });
          } else {
            Toast({
              message: "服务器异常",
              position: "middle",
              duration: 1000,
              iconClass: "glyphicon glyphicon-remove"
            });
          }
        })
        .catch(function() {
          console.log("服务器异常！");
        });
    }
  }
};
</script>
<style>
</style>